<template>
  <div class="wuliu">
    <top></top>
    <div v-loading='loading' style="padding: 20px;">

      <div class="kflexc">
        <el-button type="danger" @click="createNumber" class="wrap">创建号池</el-button>
      </div>
      <el-table :data="list" border style="width: 100%; margin: 20px 0;" ref="multipleTable">
        <el-table-column align="center" prop="name" label="号池"></el-table-column>
        <el-table-column align="center" prop="type_name" label="运营商"></el-table-column>
        <el-table-column align="center" label="号池类别">
          <template slot-scope="scope"> {{ scope.row.number_pool_type === 1 || scope.row.number_pool_type === 0 ? '本地号池' : '线上号池' }}</template>
        </el-table-column>
        <el-table-column align="center" prop="count_all" label="号码数量"></el-table-column>
        <el-table-column align="center" prop="sold_count" label="已售出数量"></el-table-column>
        <el-table-column align="center" prop="available" label="剩余号码"></el-table-column>
        <el-table-column align="center" label="自动更新" width="180px">
          <template slot-scope="scope">
            <div class="operate" v-if="scope.row.number_pool_type === 2">
              <el-switch
                v-model="scope.row.auto_run_switch"
                active-color="#2678FF"
                @change="(value)=>changeSwitch(value,scope.row)"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
              <div class="operate_time">{{scope.row.number_update_interval}}分钟</div>
              <img
                v-if="scope.row.auto_run_switch == 1"
                class="operate_image"
                @click="changeSwitch(1,scope.row)"
                src="https://file.storep.91haoka.cn/test-img/1736297117877.png"
                alt
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="created_at" label="创建时间"></el-table-column>

        <el-table-column align="center" label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="text" style="margin-left: 0;" size="mini" @click="edit(scope.row)">编辑</el-button>
            <el-button
              type="text"
              style="margin-left: 0;"
              size="mini"
              @click="logkai2(scope.row)"
            >管理号码</el-button>
            <el-button type="text" style="margin-left: 0;" size="mini" @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="text-align: right;"
        background
        layout="total,prev, pager, next"
        :current-page="all.page"
        @current-change="fanye"
        :page-size="all.page_size"
        :total="total"
      ></el-pagination>
    </div>
    <!--
       这边是创建号池的弹窗
    -->
    <el-dialog
      :title="createNumbertle"
      center
      :visible.sync="createNumberModal"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="createNumber_input">
        <div>
          <el-select placeholder="所属运营商" v-model="field.type">
            <el-option v-for="item in sanlist" :label="item.name" :key="item.id" :value="item.id"></el-option>
          </el-select>
        </div>
        <div style="margin-top: 10px;">
          <el-input placeholder="请输入号池名称" v-model="field.name"></el-input>
        </div>
        <div style="margin-top: 10px;">
          <el-select placeholder="请选择号池" v-model="field.number_pool_type">
            <el-option label="本地号池" :value="1"></el-option>
            <el-option label="线上号池" :value="2"></el-option>
          </el-select>
        </div>
        <div style="margin-top: 10px;" v-if="field.number_pool_type == 2">
          <el-select placeholder="线上接口" v-model="field.channel_id" filterable>
            <el-option
              v-for="item in infoArray.channel_id"
              :label="item.user_defined_name"
              :key="item.channel_id"
              :value="item.channel_id"
            ></el-option>
          </el-select>
        </div>
        <div style="margin-top: 10px;" v-if="field.number_pool_type == 2">
          <el-input placeholder="上游产品编码" v-model="field.upstream_product_name"></el-input>
        </div>
        <div style="margin-top: 10px;" v-if="field.number_pool_type == 2">
          <el-cascader
            :props="{ multiple: true,children:'child',label:'name',value:'code' }"
            placeholder="取号地区选择"
            :options="cityList"
            collapse-tags
            v-model="field.address_obj"
            @change="changeaddress"
          ></el-cascader>
        </div>
        <div style="margin-top: 10px;" class="tip" v-if="field.number_pool_type == 2">
          <el-input placeholder="本地缓存数量，上限10000" v-model="field.total_number_count"></el-input>
          <el-tooltip class="item" effect="dark" content="请按照上游接口情况谨慎填写" placement="top-start">
            <div class="tip_tooltip">!</div>
          </el-tooltip>
        </div>
      </div>
      <span slot="footer">
        <el-button type="info" round @click="createNumberModal = false">取消</el-button>
        <el-button type="danger" round @click="submit">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="自动更新间隔" :visible.sync="updateModal" width="450px" center>
      <div class="createNumber_input">
        <el-select placeholder="更新间隔" v-if="!!selectObj" v-model="number_update_interval">
          <el-option :key="item" v-for="item in intervals" :value="item.value" :label="item.title"></el-option>
        </el-select>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="quxiao" class="cancel">取 消</el-button>
        <el-button type="primary" @click="onRefer" class="define">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import top from '../top.vue'
import axios from "axios";
import moment from "moment";
import XLSX from "xlsx";
import { read, utils } from "xlsx";
import DataJson from "./data.json";
import {
  provinceAndCityData,
  CodeToText,
  TextToCode
} from "element-china-area-data";

export default {
  components:{
      top
  },
  name: "wuliu",
  data() {
    return {
      number_update_interval: null,
      intervals: [],
      infoArray: {
        channel_id: [],
        regions: []
      },
      cityList: [],
      field: {
        type: "",
        name: "",
        number_pool_type: "",
        channel_id: ""
      },
      error: "",
      isSubmitDisabled: false,
      updateModal: false,
      createNumbertle: "",
      createNumberModal: false,
      sanlist: [
        {
          name: "中国联通",
          id: 1
        },
        {
          name: "中国移动",
          id: 2
        },
        {
          name: "中国电信",
          id: 3
        },
        {
          name: "中国广电",
          id: 4
        }
      ],
      all2: {
        name: "",
        // cate:3,
        type: "",
        pool_id: ""
      },
      loading: false,
      list: "",
      all: {
        page: 1,
        page_size: 20
        // cate:3
      },
      total: 0,
      shopid: "",
      log: false,
      selectObj: null,
      intervals: []
    };
  },
  created() {
    //店铺权限问题
    this.shopid = JSON.parse(localStorage.getItem("SHOP")).shop_id;
    this.getlist();
    //获取当前年月
    // this.getNowDate()
    // console.log(this.vsdate())
    this.getData();

    this.getInterfaceData();
  },
  mounted() {},
  methods: {
    getData() {
      let data = DataJson.map(item => {
        return {
          ...item,
          child: item.child.map(obj => {
            delete obj.child;
            return obj;
          })
        };
      });
      this.cityList = JSON.parse(JSON.stringify(data));

      console.log("data", data);
    },
    // 因为没用el-form-item，需要自己写校验，输入号码不能大于10000且必须为数字
    //  validateNumberCount() {
    //   const numberCount = parseInt(this.field.total_number_count, 10);

    //   if (isNaN(numberCount)) {
    //     this.error = '请输入数字';
    //     this.isSubmitDisabled = true;
    //   } else if (numberCount > 10000) {
    //     this.error = '本地缓存数量不能大于10000';
    //     this.isSubmitDisabled = true;
    //   } else {
    //     this.error = '';
    //     this.isSubmitDisabled = false;
    //   }
    // },

    quxiao() {
      this.updateModal = false;
      this.getlist();
    },
    onRefer() {
      if (this.number_update_interval === null) {
        this.$message.error("请选择更新间隔");
        return;
      }
      axios
        .post("/api/plan-market/pool/task/config", {
          pool_id: this.selectObj.id,
          // task_ids: JSON.stringify([this.selectObj.tasks[0].params.id]),
          auto_run_switch: this.selectObj.auto_run_switch,
          number_update_interval_increase: String(this.number_update_interval)
        })
        .then(response => {
          if (response.data.msg.code == 0) {
            this.$message.success(`更新间隔时间设置成功`);
            this.updateModal = false;
            this.getlist();
          } else {
            this.$message.error(response.data.msg.info);
          }
        });
    },
    changeSwitch(value, row) {
      console.log("value", value);
      if (value == 1) {
        this.updateModal = true;
        this.selectObj = { ...row, auto_run_switch: value };
        this.intervals = row.number_update_interval_select;
        this.number_update_interval = row.number_update_interval_select.find(
          item => item.selected
        ).value;
      } else {
        axios
          .post("/api/plan-market/pool/task/config", {
            pool_id: row.id,
            task_id: row.tasks[0].params.id,
            auto_run_switch: value
          })
          .then(response => {
            if (response.data.msg.code == 0) {
              this.$message.success(`自动更新已关闭`);
            } else {
              this.$message.error(response.data.msg.info);
            }
          });
      }
    },
    changeaddress(v) {
      console.log("changeaddress", v);
      // if (v && v.length > 0) {
      //   console.log("CodeToText", CodeToText[v[0]], CodeToText[v[1]]);
      //   this.field.address_province = CodeToText[v[0]];
      //   this.field.address_city =['省直辖县级行政区划','市辖区'].indexOf(CodeToText[v[1]])!=-1?CodeToText[v[0]] : CodeToText[v[1]];
      // } else {
      //   this.field.address_province = "";
      //   this.field.address_city = "";
      // }
      if (v && v.length > 0) {
        console.log("CodeToText", CodeToText[v[0]], CodeToText[v[1]]);
        this.field.address_province = CodeToText[v[0]];
        this.field.address_city = CodeToText[v[1]];
        // 选择省直接将市全选
        if (v.length === 1) {
          const province = this.cityList.find(city => city.value === v[0]);
          if (province && province.children) {
            this.field.address_obj = [
              province.value,
              ...province.children.map(child => child.value)
            ];
          }
        }
      } else {
        this.field.address_province = "";
        this.field.address_city = "";
      }
    },

    submit() {
      // let params = {
      //   address_province: this.field.address_province,
      //   address_city: this.field.address_city,
      //   total_number_count: this.field.total_number_count,
      //   upstream_product_name: this.field.upstream_product_name
      // };
      // if (this.field.paramsId) {
      //   params.id = this.field.paramsId;
      // }
      let data = {
        type: this.field.type,
        name: this.field.name,
        number_pool_type: this.field.number_pool_type,
         total_number_count: this.field.total_number_count,
      };
      if (this.field.number_pool_type == 2) {
        if (this.field.address_obj && this.field.address_obj.length < 1) {
          this.$message.error("请选择地址");
          return;
        }
        data.channel_params = JSON.stringify(
          this.field.address_obj.length > 0
            ? this.field.address_obj.map(item => {
                console.log("item", item);
                let address_province = this.getText(DataJson, item[0]);
                let address_city = this.getText(DataJson, item[1]);

                return {
                  channel_id: this.field.channel_id,
                  params: {
                    address_province: address_province,
                    address_city: address_city,

                    upstream_product_name: this.field.upstream_product_name
                  }
                };
              })
            : []
        );
      }
      if (this.field.id) {
        data.pool_id = this.field.id;
      }

      axios.post("/api/plan-market/pool/store", data).then(response => {
        if (response.data.msg.code == 0) {
          this.$message.success(`操作成功`);
          this.getlist();
          this.createNumberModal = false;
        } else {
          this.$message.error(response.data.msg.info);
        }
      });
    },
    // 这边是创建号池
    createNumber() {
      this.createNumbertle = "创建号池";
      this.createNumberModal = true;
      this.field = {};
    },
    getInterfaceData() {
      axios
        .get("/api/plan-market/upstream/channel/config/list")
        .then(response => {
          if (response.data.msg.code == 0) {
            this.infoArray.channel_id = response.data.data;
            console.log("infoArray.channel_id:", response);
          } else {
            this.$message.error(response.data.msg.info);
          }
        });
    },
    // logkai2: function(item) {
    //   const { task_completed_at, task_exception } = item.task_info_show;
    //   if (JSON.stringify(task_completed_at) === '{}' || JSON.stringify(task_exception) === '{}') {
    //     this.$router.push(
    //       "/gongju/shanghao/haoma?id=" +
    //         item.id +
    //         "&completed_at=" +
    //         encodeURIComponent(task_completed_at.completed_at) +
    //         "&exception=" +
    //         encodeURIComponent(task_exception.exception)
    //     );
    //   } else {
    //     this.$router.push("/gongju/shanghao/haoma?id=" + item.id);
    //   }
    // },
    logkai2: function(item) {
      const { task_completed_at, task_exception } = item.task_info_show;

      let query = { id: item.id };

      if (task_completed_at && JSON.stringify(task_completed_at) !== "{}") {
        query.completed_at = encodeURIComponent(task_completed_at.completed_at);
      }

      if (task_exception && JSON.stringify(task_exception) !== "{}") {
        query.exception = encodeURIComponent(task_exception.exception);
      }

      this.$router.push({
        path: "/gongju/shanghao/haoma",
        query: query
      });
    },
    logkai: function(item) {
      if (item) {
        this.all2 = {
          name: item.name,
          // cate:item.cate,
          type: item.type,
          pool_id: item.id
        };
      } else {
        this.all2 = {
          name: "",
          // cate:3,
          type: "",
          pool_id: ""
        };
      }
      console.log(this.all2);
      this.log = true;
    },
    readExcel1(files) {
      return new Promise((res, rej) => {
        var that = this;
        if (files.length <= 0) {
          return;
        }
        if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
          this.$Message.error("上传格式不正确，请上传xls或者xlsx格式");
          return;
        }
        const fileReader = new FileReader();
        fileReader.onload = ev => {
          try {
            const data = ev.target.result;
            const workbook = read(data, {
              type: "binary"
            });
            // 取第一张表
            const wsname = workbook.SheetNames[0];
            // 生成json表格内容
            const ws = utils.sheet_to_json(workbook.Sheets[wsname]);
            console.log(ws);
            // 后续为自己对ws数据的处理
            res(ws);
          } catch (e) {
            return false;
            rej(e);
          }
        };
        fileReader.readAsBinaryString(files[0]);
      });
    },

    uploasd2(file, fileList) {
      var that = this;
      let files = {
        0: file
      };
      let data = {
        pool_id: "",
        numbers: []
      };

      let ff = this.readExcel1(files);
      ff.then(res => {
        res.forEach(item => {
          let obj = {
            mobile: item["手机号码"],
            province: item["省"],
            city: item["市"]
          };
          data.numbers.push(obj);
        });

        axios.post("/api/plan-market/numbers/import", data).then(response => {
          if (response.data.msg.code == 0) {
            this.$message.success(`导入成功`);
            this.getlist();
          } else {
            this.$message.error(response.data.msg.info);
          }
        });
      });
    },

    //统计

    search: function() {
      this.all.page = 1;
      this.getlist();
    },
    //翻页
    fanye: function(page) {
      this.loading = true;
      this.all.page = page;
      this.getlist();
    },
    //获取列表
    getlist: function() {
      axios
        .get("/api/plan-market/pool/list", { params: this.all })
        .then(response => {
          if (response.data.msg.code == 0) {
            this.list = response.data.data.data;
            this.total = response.data.data.total;
            this.loading = false;
          } else {
            this.$message.error(response.data.msg.info);
          }
        });
    },

    //下载模板
    xiazai: function() {
      const a = document.createElement("a");
      a.setAttribute("download", "订单重复查询.xlsx");
      a.setAttribute(
        "href",
        location.origin + location.pathname + "static/dingdanchongfu.xlsx"
      );
      a.click();
    },

    //真下载
    xiazai2: function(dizhi) {
      var a = document.createElement("a");

      a.setAttribute("href", location.origin + "/" + dizhi);
      a.click();
    },
    findNameById(data, targetId) {
      // 遍历数据数组
      for (let item of data) {
        // 检查当前项的ID是否匹配
        if (item.name === targetId) {
          return item.code; // 找到匹配项，返回name
        }
        // 如果当前项有children，递归查找
        if (item.child && item.child.length > 0) {
          const result = this.findNameById(item.child, targetId);
          if (result) {
            return result; // 在子数组中找到了匹配项，返回name
          }
        }
      }
      // 没有找到匹配项，返回null或undefined（或者你可以抛出一个错误）
      return null;
    },
    findNameBy(data, targetId, targetId2) {
      if (targetId && targetId2) {
        let obj = data.find(item => item.code == targetId);
        console.log("obj", obj, targetId, targetId2);
        let obj2 = obj.child.find(item => item.name == targetId2);
        console.log("obj2", obj2);
        return obj2.code;
      }
      return;
    },
    getText(data, code) {
      // 遍历数据数组
      for (let item of data) {
        // 检查当前项的ID是否匹配
        if (item.code === code) {
          return item.name; // 找到匹配项，返回name
        }
        // 如果当前项有children，递归查找
        if (item.child && item.child.length > 0) {
          const result = this.getText(item.child, code);
          if (result) {
            return result; // 在子数组中找到了匹配项，返回name
          }
        }
      }
      // 没有找到匹配项，返回null或undefined（或者你可以抛出一个错误）
      return null;
    },
    edit(row) {
      let obj = row.tasks.length > 0 ? row.tasks[0] : {};
      let obj2 = row.tasks.length > 0 ? row.tasks[0].params : {};
      let address_obj = [];

      if (obj2 && obj2.address_city && obj2.address_province) {
        // address_obj.push(address_province_code);
        // if (address_province_code != address_city_code) {
        //   address_obj.push(address_city_code);
        // }
        row.regions &&
          row.regions.forEach(item => {
            if (item.province) {
              item.cities.forEach(item2 => {
                console.log("item2", item2);
                let address_province_code = this.findNameById(
                  this.cityList,
                  item.province
                );
                let address_city_code = this.findNameBy(
                  this.cityList,
                  address_province_code,
                  item2
                );
                console.log("address_province_code", address_province_code);
                console.log("address_city_code", address_city_code);

                address_obj.push([address_province_code, address_city_code]);
              });
            }
          });
      }
       this.field = { ...obj, ...row, ...obj2, address_obj, paramsId: obj2.id,number_pool_type:[0,1].findIndex(item=>item==row.number_pool_type)!=-1?1:2 };
      console.log("this.field", this.field);
      this.field.id = row.id;
      this.createNumbertle = "编辑号池";
      this.createNumberModal = true;
    },
    del(row) {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          axios
            .post("/api/plan-market/pool/delete", {
              pool_id: row.id
            })
            .then(response => {
              if (response.data.msg.code == 0) {
                this.$message.success(`操作成功`);
                this.getlist();
              } else {
                this.$message.error(response.data.msg.info);
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    }
  },
  watch: {
    updateModal: function(val) {
      if (!val) {
        this.number_update_interval = null;
        this.selectObj = {};
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.operate {
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  cursor: pointer;
  &_time {
    color: #bcbcbc;
    font-size: 14px;
    margin: 0 8px;
  }
  &_image {
    height: 15px;
  }
}
.tip {
  display: flex;
  width: 100%;
  justify-content: space-between;
  &_tooltip {
    width: 25px;
    height: 25px;
    border-radius: 50%;
    background: #b0b0b0;
    color: white;
    font-size: 15px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 10px;
  }
}
.cancel {
  width: 112px;
  height: 44px;
  border-radius: 25px;
  border: 1px solid #e3e8f1;
  background: white;
}
.define {
  width: 112px;
  height: 44px;
  border-radius: 25px;
  background: #2974FF;
  border: 0;
}
/deep/ .el-dialog {
  border-radius: 12px;
}
/deep/ .wrap {
  width: 156px;
  height: 44px;
  border-radius: 25px;
}
.wuliu {
  .powertop {
    display: flex;
    background: #f9f9f9;
  }
  .powertopli {
    flex-basis: 180px;
    line-height: 50px;
    border-bottom: 3px #f9f9f9 solid;
    color: #727272;
    border-right: 1px #f9f9f9 solid;
    font-size: 16px;
    text-align: center;
  }
  .router-link-active {
    background: #ffffff;
    border-bottom: 3px #2974FF solid;
  }
  /deep/ .el-pagination.is-background .btn-prev:disabled {
    background: rgba(246, 246, 246, 0.3);
    border: 1px rgba(167, 167, 167, 0.3) solid;
  }
  /deep/ .el-pagination.is-background .btn-next:disabled {
    background: rgba(246, 246, 246, 0.3);
    border: 1px rgba(167, 167, 167, 0.3) solid;
  }
  /deep/ .el-pagination.is-background .btn-next {
    background: rgba(246, 246, 246, 1);
    border: 1px rgba(167, 167, 167, 1) solid;
  }
  /deep/ .el-pagination.is-background .btn-prev {
    background: rgba(246, 246, 246, 1);
    border: 1px rgba(167, 167, 167, 1) solid;
  }
  /deep/ .el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: #2974FF;
  }
  /deep/ .el-pagination.is-background .el-pager li:not(.disabled).active:hover {
    color: #fff;
  }
  /deep/ .el-pagination.is-background .el-pager li:not(.disabled):hover {
    color: #2974FF;
  }
  /deep/ .el-pager li {
    border-radius: 14px;
    background: rgba(255, 255, 255, 1);
    border: 1px rgba(167, 167, 167, 0.3) solid;
  }
  /deep/ .btn-prev {
    border-radius: 14px;
    padding: 0 10px;
  }
  /deep/ .btn-next {
    border-radius: 14px;
    padding: 0 10px;
  }

  /deep/ .el-table th {
    background: rgb(246, 246, 246);
  }
  /deep/ .el-input__inner {
    line-height: 36px;
    height: 36px;
    font-size: 12px;
    background: rgb(247, 248, 250);
    border: 0;
  }
  /deep/ .el-date-editor .el-range-input {
    background: rgb(247, 248, 250);
  }
  /deep/ .el-button {
    padding: 11px 23px !important;
  }
  /deep/ .el-button--mini {
    padding: 6px 15px !important;
  }
  /deep/ .el-button--danger {
    color: #fff;
    background-color: #2974FF;
    border-color: #2974FF;
  }
  .team {
    background: #f9f9f9;
  }
}
/deep/ .createNumber_input .el-input__inner {
  width: 400px !important;
  height: 45px !important;
}
</style>
